// 公共工具函数库

/**
 * 显示Toast提示
 * @param {string} title - 提示内容
 * @param {string} icon - 图标类型: success, error, loading, none
 * @param {number} duration - 持续时间(毫秒)
 */
function showToast(title, icon = 'none', duration = 2000) {
  wx.showToast({
    title: title,
    icon: icon,
    duration: duration
  })
}

/**
 * 显示加载提示
 * @param {string} title - 提示内容
 */
function showLoading(title = '加载中...') {
  wx.showLoading({
    title: title,
    mask: true
  })
}

/**
 * 隐藏加载提示
 */
function hideLoading() {
  wx.hideLoading()
}

/**
 * 显示模态对话框
 * @param {string} title - 标题
 * @param {string} content - 内容
 * @param {boolean} showCancel - 是否显示取消按钮
 */
function showModal(title, content, showCancel = true) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: title,
      content: content,
      showCancel: showCancel,
      success: (res) => {
        if (res.confirm) {
          resolve(true)
        } else if (res.cancel) {
          resolve(false)
        }
      },
      fail: reject
    })
  })
}

/**
 * 页面跳转
 * @param {string} url - 页面路径
 * @param {string} type - 跳转类型: navigate, redirect, switchTab, reLaunch
 */
function navigateTo(url, type = 'navigate') {
  const methods = {
    navigate: wx.navigateTo,
    redirect: wx.redirectTo,
    switchTab: wx.switchTab,
    reLaunch: wx.reLaunch
  }
  
  const method = methods[type] || wx.navigateTo
  method({ 
    url,
    fail: (err) => {
      console.error('页面跳转失败:', url, err)
      showToast('页面跳转失败', 'none')
    }
  })
}

/**
 * 返回上一页
 * @param {number} delta - 返回的页面数
 */
function navigateBack(delta = 1) {
  wx.navigateBack({ delta })
}

/**
 * 格式化日期
 * @param {Date|string|number} date - 日期对象、时间戳或日期字符串
 * @param {string} format - 格式化模板
 * @returns {string} 格式化后的日期字符串
 */
function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 计算相对时间
 * @param {Date|string|number} date - 日期
 * @returns {string} 相对时间描述
 */
function timeAgo(date) {
  if (!date) return ''
  
  const now = new Date()
  const past = new Date(date)
  const diff = now - past
  
  const seconds = Math.floor(diff / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  
  if (seconds < 60) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return formatDate(date, 'YYYY-MM-DD')
}

/**
 * 防抖函数
 * @param {Function} fn - 要执行的函数
 * @param {number} delay - 延迟时间(毫秒)
 * @returns {Function} 防抖后的函数
 */
function debounce(fn, delay = 300) {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

/**
 * 节流函数
 * @param {Function} fn - 要执行的函数
 * @param {number} delay - 延迟时间(毫秒)
 * @returns {Function} 节流后的函数
 */
function throttle(fn, delay = 300) {
  let last = 0
  return function(...args) {
    const now = Date.now()
    if (now - last > delay) {
      last = now
      fn.apply(this, args)
    }
  }
}

/**
 * 设置存储数据
 * @param {string} key - 键名
 * @param {any} data - 数据
 */
function setStorage(key, data) {
  try {
    wx.setStorageSync(key, data)
    return true
  } catch (e) {
    console.error('存储数据失败:', e)
    return false
  }
}

/**
 * 获取存储数据
 * @param {string} key - 键名
 * @returns {any} 数据
 */
function getStorage(key) {
  try {
    return wx.getStorageSync(key)
  } catch (e) {
    console.error('获取数据失败:', e)
    return null
  }
}

/**
 * 删除存储数据
 * @param {string} key - 键名
 */
function removeStorage(key) {
  try {
    wx.removeStorageSync(key)
    return true
  } catch (e) {
    console.error('删除数据失败:', e)
    return false
  }
}

/**
 * 清空所有存储数据
 */
function clearStorage() {
  try {
    wx.clearStorageSync()
    return true
  } catch (e) {
    console.error('清空数据失败:', e)
    return false
  }
}

/**
 * 复制文本到剪贴板
 * @param {string} text - 要复制的文本
 */
function copyText(text) {
  return new Promise((resolve, reject) => {
    wx.setClipboardData({
      data: text,
      success: () => {
        showToast('复制成功', 'success')
        resolve(true)
      },
      fail: reject
    })
  })
}

/**
 * 拨打电话
 * @param {string} phoneNumber - 电话号码
 */
function makePhoneCall(phoneNumber) {
  wx.makePhoneCall({
    phoneNumber: phoneNumber,
    fail: (err) => {
      showToast('拨打失败', 'error')
      console.error('拨打电话失败:', err)
    }
  })
}

/**
 * 预览图片
 * @param {Array<string>} urls - 图片链接数组
 * @param {number} current - 当前显示图片的索引
 */
function previewImage(urls, current = 0) {
  wx.previewImage({
    urls: urls,
    current: urls[current]
  })
}

/**
 * 获取系统信息
 * @returns {Object} 系统信息
 */
function getSystemInfo() {
  try {
    return wx.getSystemInfoSync()
  } catch (e) {
    console.error('获取系统信息失败:', e)
    return {}
  }
}

/**
 * 显示分享菜单
 */
function showShareMenu() {
  wx.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
}

/**
 * 获取用户授权
 * @param {string} scope - 授权类型
 */
function authorize(scope) {
  return new Promise((resolve, reject) => {
    wx.authorize({
      scope: scope,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 数字格式化
 * @param {number} num - 数字
 * @returns {string} 格式化后的数字
 */
function formatNumber(num) {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

module.exports = {
  showToast,
  showLoading,
  hideLoading,
  showModal,
  navigateTo,
  navigateBack,
  formatDate,
  timeAgo,
  debounce,
  throttle,
  setStorage,
  getStorage,
  removeStorage,
  clearStorage,
  copyText,
  makePhoneCall,
  previewImage,
  getSystemInfo,
  showShareMenu,
  authorize,
  formatNumber
}

